package models

import (
	"encoding/json"
	"github.com/beego/beego/v2/client/orm"
)

type OptometryData struct {
	Id          int64      `json:"id"`
	Optometry   *Optometry `orm:"rel(fk);null;on_delete(do_nothing)" json:"-"`
	TypeName    string     `json:"type_name"`
	EyeType     string     `json:"eye_type"`
	Sph         string     `json:"sph"`
	Cyl         string     `json:"cyl"`
	AxialView   string     `json:"axial_view"`
	PdJin       string     `json:"pd_jin"`
	PdYuan      string     `json:"pd_yuan"`
	Mrp         string     `json:"mrp"`
	Nv          string     `json:"nv"`
	Cv          string     `json:"cv"`
	AddInfo     string     `json:"add_info"`
	Pass        string     `json:"pass"`
	V           string     `json:"v"`
	Bc          string     `json:"bc"`
	TotalPdJin  string     `json:"total_pd_jin"`
	TotalPdYuan string     `json:"total_pd_yuan"`
	Diameter    string     `json:"diameter"`
	BaseCurve   string     `json:"base_curve"`
}

func (a *OptometryData) TableName() string {
	return OptometryDataTableName()
}

func OptometryDataTableName() string {
	return TableName("ar_optometry_data")
}

//按验光单获取明细数据
func GetOptometryDataList(opt_id int64) map[string]map[string]interface{} {
	data := make([]*OptometryData, 0)
	orm.NewOrm().QueryTable(OptometryDataTableName()).Filter("optometry_id", opt_id).All(&data)
	if len(data) == 0 {
		return nil
	}
	map_data := make(map[string]map[string]interface{})
	for k, _ := range data {
		value := data[k]
		if _, ok := map_data[value.TypeName]; ok { //存在验光类型
			map_data[value.TypeName][value.EyeType] = value
		} else {
			c_map_data := make(map[string]interface{})
			c_map_data[value.EyeType] = value
			map_data[value.TypeName] = c_map_data
		}
	}
	return map_data
}

//更新指定验光单
func UpdateOptometryDataForOptId(o orm.TxOrmer, opt_id int64, chufang string) error {
	//处方处理
	opt_data := make([]*OptometryData, 0)
	if len(chufang) > 0 {
		if err := json.Unmarshal([]byte(chufang), &opt_data); err != nil {
			return err
		}
		o.Raw("DELETE FROM "+OptometryDataTableName()+" WHERE optometry_id= ?", opt_id).Exec() //清除现有的验光明细
		for k, _ := range opt_data {
			opt_data[k].Optometry = &Optometry{Id: opt_id}
		}
		if _, err := o.InsertMulti(len(opt_data), opt_data); err != nil {
			return err
		}
	}
	return nil
}
